package com.edou.member.controller.admin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.edou.auth.entity.User;
import com.edou.base.constant.SessionConstant;
import com.edou.base.controller.BaseController;
import com.edou.base.token.TokenValidate;
import com.edou.member.entity.MemberCompany;
import com.edou.member.form.MemberCompanyForm;
import com.edou.member.service.IMemberCompanyService;



/**
 * 会员所属企业信息
 * @creator     
 * @create-time 2016/4/25 15:00:52
 * @email admin@edou.com
 * @company www.edou.com
 * @version 1.0
 */
@Controller("memberCompanyAdminController")
@Scope("prototype")
@RequestMapping("/admin/member/company")
public class MemberCompanyAdminController extends BaseController {

	@Resource(name = "memberCompanyServiceImpl")
	private IMemberCompanyService memberCompanyService;
	


	/**
	 * 首页
	 * @return 
	 */
	@RequestMapping(value = "/index.htm", method = RequestMethod.GET)
	public String index(){
		return "/admin/member/member_company_index";
	}

	/**
	 * 分页查询
	 * @return 
	 */
	@RequestMapping(value = "/listMemberCompanyByPage.htm", method = RequestMethod.POST)
	public void listMemberCompanyByPage(@ModelAttribute MemberCompanyForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		try{
			memberCompanyService.listMemberCompanyByPage(model.getPageResult(),model.getCondition());
			JSONObject root = toPageJson(model.getPageResult(), new String[]{"id","name","telephone","address","website"});
			ajaxPageResult(root,response);
		}catch(Exception ex){
			String msg = "查询会员所属企业信息时发生异常："+ex.getMessage();
			logger.error(msg,ex);
		}
	}

	/**
	 * 保存会员所属企业信息
	 * @return 
	 */
	@RequestMapping(value = "/edit.htm", method = RequestMethod.GET)
	public ModelAndView edit(@ModelAttribute MemberCompanyForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/member/member_company_add");
		Map<String,Object> data = view.getModel();
		if(StringUtils.isNotBlank(model.getItem().getId())){
			MemberCompany item = memberCompanyService.getMemberCompanyById(model.getItem().getId());
			data.put("item", item);
		}else{
			data.put("item", model.getItem());
		}
		


		return view;
	}

	/**
	 * 保存会员所属企业信息
	 * @return 
	 */
	@RequestMapping(value = "/saveMemberCompany.htm", method = RequestMethod.POST)
	@TokenValidate
	public ModelAndView saveMemberCompany(@ModelAttribute MemberCompanyForm model,HttpServletRequest request,HttpSession session){
		try {
			User curUser = (User)session.getAttribute(SessionConstant.CURRENT_USER);
			// 排序
			Integer sort = model.getItem().getSort() == null ? 0 : model.getItem().getSort();
			model.getItem().setSort(sort);
			if(StringUtils.isBlank(model.getItem().getId())){
				model.getItem().setCreateBy(curUser.getAccount());
				model.getItem().setUpdateBy(curUser.getAccount());
				memberCompanyService.add(model.getItem());
			}else{
				model.getItem().setUpdateBy(curUser.getAccount());
				memberCompanyService.update(model.getItem());
			}
			Map<String,String> data = new HashMap<String,String>();
			data.put("itemId", model.getItem().getId());
			return ajaxJSON(Status.success,"保存成功",data);
		} catch (Exception e) {
			String msg = "保存会员所属企业信息时发生异常：" + e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error, "保存失败，请稍后重试");
		}
	}
	/**
	 * 删除会员所属企业信息
	 * @return 
	 */
	@RequestMapping(value = "/del.htm", method = RequestMethod.POST)
	public ModelAndView del(@ModelAttribute MemberCompanyForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		try {
			memberCompanyService.delByIds(model.getSelIds().split(","));
			return ajaxJSON(Status.success,"删除成功");
		} catch (Exception e) {
			String msg = "删除会员所属企业信息时发生异常：" + e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error, "删除失败，请稍后重试");
		}
	}

	/**
	 * 加载树形菜单的信息
	 * @param pid
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/listRightByTree.htm", method = RequestMethod.POST)
	public ModelAndView listRightByTree(String pid){
		JSONArray root = new JSONArray();
		List<MemberCompany> list = memberCompanyService.listRightByParentId(pid,3);
		if(null != list && list.size() > 0){
			for (int i = 0; i < list.size(); i++){
				MemberCompany memberCompany = list.get(i);
				JSONObject json = makeRightTreeJsonForSet(memberCompany);
				
				List<MemberCompany> listChild = memberCompany.getChildRights();
				JSONArray arrayChild = new JSONArray();
				for(MemberCompany memberCompanyChild : listChild){
					JSONObject obj = makeRightTreeJsonForSet(memberCompanyChild);
					List<MemberCompany> listChildSub = memberCompanyChild.getChildRights();
					JSONArray arrayChildSub = new JSONArray();
					for(MemberCompany memberCompanyChildSub : listChildSub){
						JSONObject objSub = makeRightTreeJsonForSet(memberCompanyChildSub);
						arrayChildSub.add(objSub);
					}
					obj.put("children", arrayChildSub);
					arrayChild.add(obj);
				}
				json.put("children", arrayChild);
				root.add(json);
			}
		}
		
		Map<String,String> data = new HashMap<String,String>();
		data.put("data", root.toJSONString());
		
		return ajaxJSON(Status.success, "加载成功",data);
	}
	/**
	 * 为权限设置构建树形菜单结构
	 * @param right
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private JSONObject makeRightTreeJsonForSet(MemberCompany memberCompany) {
		JSONObject data = new JSONObject();
		data.put("id", memberCompany.getId());
		data.put("name", memberCompany.getName());
		data.put("address", memberCompany.getAddress());
		data.put("telephone", memberCompany.getTelephone());
		data.put("website", memberCompany.getWebsite());
		data.put("sort", memberCompany.getSort());
		data.put("parentId", memberCompany.getParentId());
		data.put("level", memberCompany.getLevel());
		data.put("isLeaf", memberCompany.getIsLeaf());
		return data;
	}
	
	/**
	 * 检验是否有下级
	 * @param model
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/checkParent.htm", method = RequestMethod.POST)
	public ModelAndView checkParent(@ModelAttribute MemberCompanyForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		JSONObject object = new JSONObject();
		if(StringUtils.isNotBlank(model.getItem().getId())){
			List<MemberCompany> memberCompanyList = memberCompanyService.listMemberCompanyByParentId(model.getItem().getId());
			if(memberCompanyList.size() != 0){
				// 表示有下级
				object.put("flag", 1);
			}else{
				// 表示没有下级
				object.put("flag", 0);
			}
		}
		return ajaxJSON(Status.success, object);
	}
	
}